using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using DotNetNuke.Common.Lists;

namespace Code5Systems.FormMaster.Business
{

	public partial class FormController
	{
		
#region Utility Methods
		
		
		public List<FieldRulesScriptInfo> GetAllFieldRuleScriptInfoByTarget(string targetId)
		{
			FieldRulesScriptInfo scriptInfo = null;
			List<FieldRulesScriptInfo> tFields = new List<FieldRulesScriptInfo>();
			foreach (FieldRulesScriptInfo tempLoopVar_scriptInfo in this._fieldRules)
			{
				scriptInfo = tempLoopVar_scriptInfo;
				if (scriptInfo.SourceField.FormFields.Contains(targetId))
				{
					tFields.Add(scriptInfo);
				}
			}
			
			return tFields;
			
		}
		
		public FormFieldRulesInfo GetSourceFieldByTarget(string targetId)
		{
			FormFieldRulesInfo rulesInfo = null;
			foreach (FieldRulesScriptInfo rulesScriptInfo in _fieldRules)
			{
				if (rulesScriptInfo.SourceField.FormFields.Contains(targetId))
				{
					return rulesScriptInfo.SourceField;
				}
			}
			
			return rulesInfo;
		}
		
		//Bind the Dynamic user created control names to a dropdown list
		public void BindDynamicControls(ListControl oListContol, int moduleId, bool excludeHidden = false, bool excludeCommand = true, bool excludeLabels = true, bool excludeUploads = true, bool excludeChildDropdowns = true)
		{
			XDocument xDoc = default(XDocument);
			List<ListItem> oItems = new List<ListItem>();
			FormController objFormCtl = new FormController(moduleId);
			List<FormControlInfo> aryFormControls = default(List<FormControlInfo>);
			
			oListContol.Items.Clear();
			if (objFormCtl.Pages.Count > 0)
			{
				foreach (FormPageInfo item in objFormCtl.Pages)
				{
					if (!string.IsNullOrEmpty(item.PageData))
					{
						xDoc = XDocument.Parse(item.PageData);
						aryFormControls = this.GetFormControlArray(xDoc);
						
						foreach (FormControlInfo control in aryFormControls)
						{
							
							switch (control.Type)
							{
								case ControlType.HiddenField:
									if (!excludeHidden)
									{
										oItems.Add(new ListItem(control.FieldName, control.ID));
									}
									break;
								case ControlType.SubmitButton:
									if (!excludeCommand)
									{
										oItems.Add(new ListItem(control.FieldName, control.ID));
									}
									break;
								case ControlType.Label:
									if (!excludeLabels)
									{
										oItems.Add(new ListItem(control.FieldName, control.ID));
									}
									break;
								case ControlType.FileUpload:
									if (!excludeUploads)
									{
										oItems.Add(new ListItem(control.FieldName, control.ID));
									}
									break;
								case ControlType.DropDownList:
									if (control.IsChildList && !excludeChildDropdowns)
									{
										oItems.Add(new ListItem(control.FieldName, control.ID));
									}
									else
									{
										oItems.Add(new ListItem(control.FieldName, control.ID));
									}
									break;
								default:
									oItems.Add(new ListItem(control.FieldName, control.ID));
									break;
							}
						}
						
					}
				}
				oItems.Sort((p1, p2) => p1.Text.CompareTo(p2.Text));
				oListContol.DataTextField = "Text";
				oListContol.DataValueField = "Value";
				oListContol.DataSource = oItems;
				oListContol.DataBind();
			}
		}
		
		//Bind the Dynamic user created control names to a dropdown list
		public void BindPageDynamicControls(ListControl oListContol, int moduleId, int pageNum, bool excludeHidden = false, bool excludeCommand = true, bool excludeLabels = true, bool excludeUploads = true)
		{
			XDocument xDoc = default(XDocument);
			List<ListItem> oItems = new List<ListItem>();
			FormController objFormCtl = new FormController(moduleId);
			List<FormControlInfo> aryFormControls = default(List<FormControlInfo>);
			
			oListContol.Items.Clear();
			if (objFormCtl.Pages.Count > 0)
			{
				FormPageInfo formPage = objFormCtl.Pages.Where(p => p.PageNum == pageNum).FirstOrDefault();
				if (formPage != null)
				{
					if (!string.IsNullOrEmpty(formPage.PageData))
					{
						xDoc = XDocument.Parse(formPage.PageData);
						aryFormControls = this.GetFormControlArray(xDoc);
						
						foreach (FormControlInfo control in aryFormControls)
						{
							
							switch (control.Type)
							{
								case ControlType.HiddenField:
									if (!excludeHidden)
									{
										oItems.Add(new ListItem(control.FieldName, control.ID));
									}
									break;
								case ControlType.SubmitButton:
									if (!excludeCommand)
									{
										oItems.Add(new ListItem(control.FieldName, control.ID));
									}
									break;
								case ControlType.Label:
									if (!excludeLabels)
									{
										oItems.Add(new ListItem(control.FieldName, control.ID));
									}
									break;
								case ControlType.FileUpload:
									if (!excludeUploads)
									{
										oItems.Add(new ListItem(control.FieldName, control.ID));
									}
									break;
								default:
									oItems.Add(new ListItem(control.FieldName, control.ID));
									break;
							}
						}
						
					}
				}
				oItems.Sort((p1, p2) => p1.Text.CompareTo(p2.Text));
				oListContol.DataTextField = "Text";
				oListContol.DataValueField = "Value";
				oListContol.DataSource = oItems;
				oListContol.DataBind();
			}
		}
		
		public void CreateExtTableMaskList(string[] tables)
		{
			ListController listCtl = new ListController();
			ListEntryInfo oListEntryInfo = new ListEntryInfo();
			
			oListEntryInfo.PortalID = -1;
			oListEntryInfo.ListName = "FormMasterExtTableMask";
			string tempTable;
			foreach (string table in tables)
			{
				tempTable = table;
				if (!table.StartsWith("aspnet_"))
				{
					tempTable = Code5Systems.FormMaster.Data.DataProvider.Instance().ObjectQualifier + table;
				}
				oListEntryInfo.Text = tempTable;
				oListEntryInfo.Value = tempTable;
				listCtl.AddListEntry(oListEntryInfo);
			}
		}
		
		public static int GetControlCount(FormInfo oFormInfo)
		{
			XDocument xDoc = default(XDocument);
			int count = default(int);
			
			try
			{
				xDoc = XDocument.Parse(oFormInfo.CurrentPage.PageData);
				List<XElement> result = (from c in xDoc.Elements("Form").Elements("Controls").Elements("Control") where c.Attributes("Type").First().Value != "Label" select c).ToList();
				count = result.Count;
			}
			catch (Exception ex)
			{
				DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
				count = 0;
			}
			
			return count;
			
		}
		
		public XElement GetControlElement(XDocument xDoc, string row, string col)
		{
			XElement xControl = default(XElement);
			
			xControl = (from c in xDoc.Root.Elements("Controls").Elements("Control") where c.Attributes("TableRow").First().Value == row && c.Attributes("TableCol").First().Value == col select c).FirstOrDefault();
			
			return xControl;
			
		}
		
		public XElement GetControlElement(XDocument xDoc, string controlId)
		{
			XElement xControl = default(XElement);
			
			xControl = (from c in xDoc.Root.Elements("Controls").Elements("Control") where c.Attributes("ID").First().Value == controlId select c).FirstOrDefault();
			
			return xControl;
			
		}
		
		public XElement GetValidatorControlElement(XElement xControl, ControlType type)
		{
			XElement xValidatorControl = default(XElement);
			
			xValidatorControl = (from v in xControl.Elements("Validators").Elements("Control")
								 where v.Attributes("Type").First().Value == type.ToString() 
								 select v).FirstOrDefault();
			
			return xValidatorControl;
		}
		
		internal List<FormControlInfo> GetCascadeSet(string ctlID)
		{
			List<FormControlInfo> cascadeSet = new List<FormControlInfo>();
			
			FormControlInfo cascadeSetMember = GetFormControlInfo(ctlID);
			if (cascadeSetMember != null)
			{
				// Get to the top of the set if any
				while (cascadeSetMember.CascadingList)
				{
					cascadeSetMember = GetFormControlInfo(cascadeSetMember.ParentControlID);
					if (cascadeSetMember == null)
					{
						break;
					}
				}
				
				while (cascadeSetMember != null)
				{
					cascadeSet.Add(cascadeSetMember);
					cascadeSetMember = GetFormControlInfo(cascadeSetMember.ChildControlID);
					if (cascadeSetMember == null)
					{
						break;
					}
				}
			}
			return cascadeSet;
		}
		
		public void DoLegacySerializationFixup()
		{
			XDocument xDoc = default(XDocument);
			XAttribute xAttribute = default(XAttribute);
			PropertyInfo[] properties = typeof(FormControlInfo).GetProperties();
			FormPageController pageCtlr = new FormPageController();
			
			foreach (FormPageInfo myPage in this.Pages)
			{
				xDoc = XDocument.Parse(myPage.PageData);
				IEnumerable<XElement> xControls = xDoc.Root.Descendants("Control");
				foreach (XElement xControl in xControls)
				{
					foreach (PropertyInfo prop in properties)
					{
						switch (prop.Name)
						{
							case "Validators":
								IEnumerable<XElement> xValidators = xControl.Elements("Validators").Elements("Control");
								foreach (XElement item in xValidators)
								{
									if (item.Attributes("Type").First().Value == "RequiredFieldValidator")
									{
										xControl.Attributes("Required").First().Value = "true";
									}
									foreach (XAttribute tempLoopVar_xAttribute in item.Attributes())
									{
										xAttribute = tempLoopVar_xAttribute;
										if (xAttribute.Value.ToLower() == "true")
										{
											xAttribute.Value = "true";
										}
										else if (xAttribute.Value.ToLower() == "false")
										{
											xAttribute.Value = "false";
										}
										if (xAttribute.Name == "CookieExpires")
										{
											if (string.IsNullOrEmpty(xAttribute.Value))
											{
												xAttribute.Value = "0";
											}
										}
									}
								}
								break;
							case "ListItems":
								List<XElement> xListItems = xControl.Elements().Descendants("ListItem").ToList();
								foreach (XElement item in xListItems)
								{
									foreach (XAttribute tempLoopVar_xAttribute in item.Attributes())
									{
										xAttribute = tempLoopVar_xAttribute;
										if (xAttribute.Value.ToLower() == "true")
										{
											xAttribute.Value = "true";
										}
										else if (xAttribute.Value.ToLower() == "false")
										{
											xAttribute.Value = "false";
										}
									}
								}
								break;
							case "Label":
								if (!xControl.ElementExists("Label"))
								{
									xControl.Add(new XElement("Label", xControl.Attributes("Label").First().Value));
								}
								break;
							case "FieldName":
								if (!xControl.AttributeExists("FieldName"))
								{
									xControl.Add(new XAttribute("FieldName", Utility.GetValidDbFieldName(Utility.CleanInputAll((string) (xControl.Attributes("Label").First().Value)))));
								}
								break;
							default:
								xAttribute = xControl.Attributes(prop.Name).FirstOrDefault();
								if (xAttribute != null)
								{
									switch (prop.PropertyType.Name)
									{
										case "Boolean":
											if (xAttribute.Value.ToLower() == "true")
											{
												xAttribute.Value = "true";
											}
											else
											{
												xAttribute.Value = "false";
											}
											break;
										case "Integer":
											break;
										case "Int32":
											if (string.IsNullOrEmpty(xAttribute.Value))
											{
												xAttribute.Value = "0";
											}
											break;
									}
								}
								break;
						}
					}
				}
				myPage.PageData = xDoc.ToString();
				pageCtlr.UpdateFormPage(myPage);
			}
		}
		
#endregion
		
	}
	
}
